# coding: utf-8
import pymysql


class SqlModel(object):
    def __init__(self, database="default"):
        """
        :param database: {"NAME":xx, "HOST":xx,}  跟django中 DATABASES 保持一致
        """
        from finance_c2c.local_settings import DATABASES
        database = DATABASES.get(database)
        database = {
            "host": database.get("HOST"),
            "port": database.get("PORT"),
            "user": database.get("USER"),
            "passwd": database.get("PASSWORD"),
            "db": database.get("NAME"),
            "charset": "utf8",
        }
        self.conn = pymysql.connect(**database)
        self.cursor = self.conn.cursor()

    def __del__(self):
        self.cursor.close()
        self.conn.close()
        print("mysql connect close")

def update_url():
    sql_model = SqlModel(database="klb")
    sql = "SELECT * FROM `bxweb_refactor_online`.`jinrong_productcodeurl`"
    sql_model.cursor.execute(sql)
    result = sql_model.cursor.fetchall()
    # print(len(result))
    num = 1
    for i in result:
        i_id = i[0]
        i_url = "https://site.cc.cmbimg.com/EloanAppWeb/#/home?sourceCode=" + i[1].replace("https://cmblife.cmbchina.com/EloanAppWeb/#/entryPage?sourceCode=", "")
        # print(i_url)
        update_sql = "update `bxweb_refactor_online`.`jinrong_productcodeurl` set `url`='%s' where `id`=%s;" % (i_url, i_id)
        sql_model.cursor.execute(update_sql)
        sql_model.conn.commit()
        num += 1
        print(num)

if __name__ == '__main__':
    update_url()
